import React from "react";
import {Button, Checkbox, Flex, Form, Input, message} from "antd";
import {LockOutlined, UserOutlined} from "@ant-design/icons";
import {loginAPI, userInfoAPI, userMenusAPI} from "@/api/authentication.ts";
import {useNavigate} from "react-router-dom";
import {setToken} from "@/utils/Auth.ts";
import {setUserInfo} from "@/store/UserInfoSlice.ts";
import {useDispatch} from "react-redux";
import {setMenus} from "@/utils/MuenUtils.tsx";
import {useTranslation} from "react-i18next";

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

interface ILoginFormProps {
  updateLoading: (value: boolean) => void
}

const LoginForm: React.FC<ILoginFormProps> = ({updateLoading}) => {

  const [form] = Form.useForm<{ username: string; password: string, remember: boolean }>();
  const username = Form.useWatch('username', form);
  const password = Form.useWatch('password', form);
  const remember = Form.useWatch('remember', form);

  const dispatch = useDispatch()

  const navigate = useNavigate()

  const submitLogin = async () => {
    updateLoading(true)
    try {
      // 校验登录表单项
      const validatedAttribute = await form.validateFields();
      if (validatedAttribute) {

        try {
          // 登录
          const loginRes = await loginAPI({username, password});
          const token = loginRes.data?.token || '';

          // 设置 token
          setToken(token, !remember);

          // 获取用户信息
          const userInfoRes = await userInfoAPI();
          const userInfo = userInfoRes.data;

          // 更新用户信息
          dispatch(setUserInfo(userInfo));

          // 获取用户菜单
          const userMenusRes = await userMenusAPI();
          const userMenus = userMenusRes.data || [];

          // 设置用户菜单
          setMenus(userMenus);
          // 确保 setMenus 完成后再进行导航
          await Promise.resolve();
          updateLoading(false)
          // 导航到 '/home'
          navigate('/home');
          message.success('登录成功')
        } catch (error) {
          updateLoading(false)
          console.error('Error:', error);
          // 处理错误情况
        }

      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }

  const usernameRules = [
    {required: true, message: '请输入用户名！'}
  ]
  const passwordRules = [
    {required: true, message: '请输入密码！'}
  ]
  const {t} = useTranslation();


  return (
    <Form name="login" initialValues={{remember: true}} autoComplete="off" form={form} className="login-box-right-form">
      <Form.Item<FieldType> name="username" rules={usernameRules}>
        <Input prefix={<UserOutlined/>} autoComplete="off" size="large"
               placeholder={t('login.usernamePlaceholder')}/>
      </Form.Item>


      <Form.Item<FieldType> name="password" rules={passwordRules}>
        <Input.Password autoComplete="off" prefix={<LockOutlined/>} size="large"
                        placeholder={t('login.passwordPlaceholder')}/>
      </Form.Item>

      <Form.Item>
        <Flex justify="space-between">
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>{t('login.remember')}</Checkbox>
          </Form.Item>

          <a className="login-form-forgot" href="">
            {t('login.forgotPassword')}
          </a>
        </Flex>
      </Form.Item>

      <Form.Item>
        <Button size="large" style={{width: "100%"}} type="primary" htmlType="button" onClick={submitLogin}>
          {t('login.login')}
        </Button>
      </Form.Item>
    </Form>
  )
}

export default LoginForm